<template>
  <div class="page-user">
  <div class="search">
    <el-button @click="getUserList" class="search-button">搜索</el-button>
          <el-input
            v-model="searchForm.username"
            placeholder="用户名"
            clearable
          >
          </el-input>

          <div class="title">搜索用户</div>

          <!--          <el-button type="primary" @click="dialogVisible = true" >新增-->
          <el-button type="primary" @click="dialogVisible = true" v-if="hasAuth('sys/user/add')" class="change-button">新增
          </el-button>

          <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
            <el-button type="danger" slot="reference" :disabled="delBtlStatu" class="change-button"
                       v-if="hasAuth('sys/user/delecct')">批量删除
            </el-button>
          </el-popconfirm>

          </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        width="1840"
        align="center"
        @selection-change="handleSelectionChange"
        v-if="hasAuth('sys/user')">

        <el-table-column
          type="selection" align="center"
          width="70">
        </el-table-column>

        <!-- <el-table-column
          prop="icon"
          label="头像"
          width="50">
          <template slot-scope="scope">
            <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column> -->

        <el-table-column
          prop="username" align="center"
          label="用户名"
          width="150">
        </el-table-column>
        <el-table-column
          prop="email" align="center"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile" align="center"
          label="手机号">
        </el-table-column>

        <el-table-column
          prop="state" align="center"
          label="状态"
          width="150">
          <template slot-scope="scope">
            <el-tag size="small" v-if="scope.row.state === 0" type="success">正常</el-tag>
            <el-tag size="small" v-else-if="scope.row.state === 1" type="danger">禁用</el-tag>
          </template>

        </el-table-column>
        <el-table-column
          prop="date_joined" align="center"
          width="300"
          label="创建时间"
        >
        </el-table-column>
        <el-table-column
          prop="state" align="center"
          width="400px"
          label="操作">

          <template slot-scope="scope">
            <el-button type="text" @click="roleHandle(scope.row.id)" v-if="hasAuth('user/part')">分配角色</el-button>
            <el-divider direction="vertical"></el-divider>

            <el-button type="text" @click="editHandle_pwd(scope.row.id)"
                       v-if="hasAuth('sys/user/update')">修改密码
            </el-button>
            <el-divider direction="vertical"></el-divider>

            <el-button type="text" @click="editHandle(scope.row.id)" v-if="hasAuth('sys/user/update')">编辑</el-button>
            <el-divider direction="vertical"></el-divider>

            <template>
              <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.username)">
                <el-button type="text" slot="reference" v-if="hasAuth('sys/user/delecct')">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>

      </el-table>

      <div class="pagenation" v-if="hasAuth('login_log_look')">
        <el-pagination
          small
          layout="prev, pager, next"
          :total="num"
          :page-size="page_size"
          @prev-click="prevfun"
          @next-click="nextfun"
          @current-change="currentchange"
        >
        </el-pagination>
      </div>


      <!--新增对话框-->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">

        <el-form :model="editForm" :rules="editFormRules" ref="editForm">
          <el-form-item label="用户名" prop="username" label-width="100px">
            <el-input v-model="editForm.username" autocomplete="off"></el-input>
            <!--                                    <el-alert-->
            <!--                                            title="初始密码为:123456"-->
            <!--                                            :closable="false"-->
            <!--                                            type="info"-->
            <!--                                            style="line-height: 12px;"-->
            <!--                                    ></el-alert>-->
          </el-form-item>

          <el-form-item label="邮箱" prop="email" label-width="100px">
            <el-input v-model="editForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" label-width="100px">
            <el-input v-model="editForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile" label-width="100px">
            <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="状态" prop="state" label-width="100px">
            <el-radio-group v-model="editForm.state">
              <el-radio :label="1">禁用</el-radio>
              <el-radio :label="0">正常</el-radio>
            </el-radio-group>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('editForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
        </div>
      </el-dialog>

      <!--修改对话框-->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible1"
        width="600px"
        :before-close="handleClose1">

        <el-form :model="editForm" :rules="editFormRules" ref="editForm">
          <el-form-item label="用户名" prop="username" label-width="100px">
            <el-input v-model="editForm.username" autocomplete="off"></el-input>
            <!--                                    <el-alert-->
            <!--                                            title="初始密码为:123456"-->
            <!--                                            :closable="false"-->
            <!--                                            type="info"-->
            <!--                                            style="line-height: 12px;"-->
            <!--                                    ></el-alert>-->
          </el-form-item>

          <el-form-item label="邮箱" prop="email" label-width="100px">
            <el-input v-model="editForm.email" autocomplete="off"></el-input>
          </el-form-item>
<!--          <el-form-item label="密码" prop="password" label-width="100px">-->
<!--            <el-input v-model="editForm.password" autocomplete="off"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="手机号" prop="mobile" label-width="100px">
            <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="状态" prop="state" label-width="100px">
            <el-radio-group v-model="editForm.state">
              <el-radio :label="1">禁用</el-radio>
              <el-radio :label="0">正常</el-radio>
            </el-radio-group>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('editForm')">取 消</el-button>
          <el-button type="primary" @click="repassHandle1(editForm.id)">确 定</el-button>
        </div>
      </el-dialog>
<!--      修改密码框-->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible2"
        width="600px"
        :before-close="handleClose_pwd">

        <el-form :model="updataud" :rules="editFormRules_pwd" ref="editForm">
          <el-form-item label="用户名" prop="username" label-width="100px">
            <el-input v-model="updataud.username" autocomplete="off"></el-input>
            <!--                                    <el-alert-->
            <!--                                            title="初始密码为:123456"-->
            <!--                                            :closable="false"-->
            <!--                                            type="info"-->
            <!--                                            style="line-height: 12px;"-->
            <!--                                    ></el-alert>-->
          </el-form-item>
          <el-form-item label="新密码"  label-width="100px">
            <el-input v-model="updataud.password_new" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm_pwd('editForm')">取 消</el-button>
          <el-button type="primary" @click="repassHandle2(updataud.id)">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配角色" :visible.sync="roleDialogFormVisible" width="600px">

        <el-form :model={roleForm}>
          <!--          <el-tree-->
          <!--              :data="roleTreeData"-->
          <!--              show-checkbox-->
          <!--              ref="roleTree"-->
          <!--              :check-strictly=checkStrictly-->
          <!--              node-key="id"-->
          <!--              :default-expand-all=true-->
          <!--              :props="defaultProps">-->
          <!--          </el-tree>-->

          <el-tree
            :data="roleTreeData"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps">
          </el-tree>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="roleDialogFormVisible=false">取 消</el-button>
          <el-button type="primary" @click="submitRoleHandle('roleForm')">确 定</el-button>
        </div>
      </el-dialog>

    
  </div>
</template>

<script>
import {hasAuth} from '../../global/index'

export default {
  name: "User",
  data() {
    return {
      updataud:{},
      searchForm: {},
      delBtlStatu: true,
      dialogVisible2:false,

      total: 0,
      size: 10,
      current: 1,

      dialogVisible: false,
      dialogVisible1: false,
      editForm: {},

      tableData: [],
      editFormRules_pwd: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        password_new: [
          {required: true, message: '请输入新密码', trigger: 'blur'}
        ]
      },

      editFormRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'}
        ],
        state: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ]
      },

      multipleSelection: [],

      roleDialogFormVisible: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      roleForm: {},
      roleTreeData: [],
      user_id: [],
      treeCheckedKeys: [],
      checkStrictly: true,
      page_size: 10,
      num: 0,
      page: 1,

    }
  },
  mounted() {
    this.getUserList()

    this.$axios.get(this.$settings.BASE_URL + 'prat/prat/').then(res => {
      console.log(res.data)
      this.roleTreeData = res.data.data
      console.log(this.roleTreeData)
    })

    // this.$axios.get("/sys/role/list").then(res => {
    //   this.roleTreeData = res.data.data.records
    // })
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      console.log("勾选")
      console.log(val)
      this.multipleSelection = val;

      this.delBtlStatu = val.length == 0
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val
      this.getUserList()
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose_pwd() {
      this.resetForm_pwd('editForm')
    },
    resetForm_pwd(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible2 = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },

    resetForm1(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible1 = false
      this.editForm = {}
    },
    handleClose1() {
      this.resetForm1('editForm')
    },

    getUserList() {
      this.$axios.get(this.$settings.BASE_URL + 'user/query/', {
        params: {
          username: this.searchForm.username,
          page: this.page,
        }
      }).then(res => {
        this.tableData = res.data.data.results
        this.num = res.data.data.count
        this.next = res.data.data.next
        this.previous = res.data.data.previous
      })
    },
    prev() {
      this.$axios.get(this.next).then((res) => {
        if (res.data.code == 100) {
          this.tableData = res.data.data.results
          this.num = res.data.data.count
          this.next = res.data.data.next
          this.previous = res.data.data.previous
        }
      })
    },
    next() {
      console.log(this.next)
      this.$axios.get(this.next).then((res) => {
        if (res.data.code == 100) {
          this.tableData = res.data.data.results
          this.num = res.data.data.count
          this.next = res.data.data.next
          this.previous = res.data.data.previous
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post(this.$settings.BASE_URL + 'user/create/register/', this.editForm)
            .then(res => {
              if (res.data.code == 100) {
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getUserList()
                  }
                });
                this.dialogVisible = false
              } else {
                this.$message.error('添加失败');
              }


            }).catch(res => {
            console.log('-----', res)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id) {
      console.log(id)
      console.log(id,id)
      this.$axios.get(this.$settings.BASE_URL + 'user/query/' + id + '/',).then(res => {
        this.editForm = res.data.data
        this.dialogVisible1 = true
      })
    },
    editHandle_pwd(id) {
      console.log('点我了')
      console.log(id)
      console.log('我过来了')
      this.$axios.get(this.$settings.BASE_URL + 'user/querypwd/' + id + '/',).then(res => {
        console.log(res.data)
        this.updataud = res.data.data
        console.log(this.updataud,3333333333333333333)
        this.dialogVisible2 = true
      })
    },
    delHandle(username) {

      var ids = []

      if (username) {
        ids.push(username)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.username)
        })
      }

      console.log(ids, '----------------------------------')

      this.$axios.delete(this.$settings.BASE_URL + "user/delete/delete/?username=" + ids).then(res => {
        if (res.data.code == 100) {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
              this.getUserList()
            }
          })
        } else {
          this.$message.error('删除失败');
        }

      })
    },

    roleHandle(id) {
      this.roleDialogFormVisible = true
      this.user_id = id
      this.$axios.get(this.$settings.BASE_URL + 'user/userprat/' + id + '/').then(res => {
        this.roleForm = res.data.data.pratmodels_id
        console.log(res.data.data.pratmodels_id, '-----------')
        let roleIds = []
        res.data.data.pratmodels_id.forEach(row => {
          roleIds.push(row.id)
        })

        this.$refs.tree.setCheckedKeys(roleIds)
      })
    },
    submitRoleHandle(formName) {
      var roleIds = this.$refs.tree.getCheckedKeys()


      console.log(roleIds)
      console.log(this.roleForm.id)
      this.$axios.post(this.$settings.BASE_URL + "user/userpartcreate/", {
        'id': this.user_id,
        'part': roleIds
      }).then(res => {
        if (res.data.code == 100) {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
              this.getUserList()
            }
          });

          this.roleDialogFormVisible = false
        } else {
          this.$message.error('修改失败');
        }

      })
    },
    repassHandle(id, username) {
      console.log(id)
      this.$confirm('将重置用户【' + username + '】的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put(this.$settings.BASE_URL + "user/update/" + id + '/', {
          'username': username,
          'password': '123456'
        }).then(res => {
          if (res.data.code == 100) {
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
              }
            });
          } else {
            this.$message.error('修改失败');
          }

        })
      })
    },
    repassHandle1(id) {
      this.$axios.put(this.$settings.BASE_URL + "user/put/" + id + '/', this.editForm).then(res => {
        if (res.data.code == 100) {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
            }
          });
          this.dialogVisible1 = false
        } else {
          this.$message.error('修改失败');
        }
      })
    },
    repassHandle2(id) {

        this.$axios.put(this.$settings.BASE_URL + "user/updatepwd/" + id + '/', {
          'username': this.updataud.username,
          'password': this.updataud.password_new,
        }).then(res => {
          if (res.data.code == 100) {
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
              }
            });
            this.dialogVisible2=false
          } else {
            this.$message.error('修改失败');
          }

        })
    },
    prevfun(value) {
      this.page = value
      //value拿到的当前的页码，点击上一页触发该函数
      this.loginlog()
    },
    nextfun(value) {
      this.page = value
      //value拿到页码，点击下一页触发该函数
      this.loginlog()
    },
    currentchange(value) {
      this.page = value
      //页码发生变化会触发，这个用来触发点击页码时触发的。
      this.loginlog()
    },
  }
}
</script>

<style lang="less">
.page-user {
  overflow: auto; //高度超出显示滚动条
  height: @h*1000vh;

  // 检测屏幕宽度
  @media screen and (min-width: 1000px) and (max-width: 1500px) {

    // 屏幕宽度在1000 到 1500之间
    .el-button {
      height: @h*40vh;
      line-height: 1;
      padding: 5px 8px;
      font-size: 1rem;
    }



  }
  .el-table--enable-row-hover .el-table__body tr:hover>td{
    background: #404040;
  }
  .el-table{
    margin: @h*30vh @w*30vw @h*20vh;
    // padding-top: @h*10vh;
    background: #404040;
    width:  @w*1860vw;
    height: @h*820vh;
    th{
      color: #fff;
      background: #404040;
    }
    td{
      background: #2e2e2e;
      color: #fff;
    }
    
    
  }
  .el-pagination{
    float: right;
    margin-right: @w*30vw;

  }
  .search{
      border-bottom: 1px solid #404040;
      // float: right;
      height: @h*60vh;
      margin: @h*20vh @w*30vw;
      .title{
        float:right;
        line-height:  @h*40vh;
      }
      .change-button{
        float: left;
        margin-right:@w*20vw;
      }
      .el-input{
        float: right;
        width: @w*300vw;
        height: @h*40vh;
        margin: 0 @w*20vw;
        background: #2E2E2E;
        border-radius: 0px;
      }
      .el-input__inner{
        background: #4d4d4d;
        border: none;
      }
      .search-button{
        background: #00A0E9;
        color: #fff;
        border: none;
        float:right;
      }
    }
}
</style>